﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using UnityEngine.EventSystems;

public class PlayerControl : MonoBehaviour
{
    public GameObject _Start;
    public GameObject End;
    GameObject StarWindow;
    private bool IsMouseDown = false;
    private int PlayerID;
   
    private void Start()
    {
        StarWindow = GameObject.Find("Canvas").transform.Find("StatPanel").gameObject;
        PlayerID = GetComponent<PlayerAcion>().PlayerID;
        GameManager.Instance.PlayerID = PlayerID;
    }

    private void Update()
    {
        End= GetEnd();
        if(End!=null)
        {
            GetStart();
        }
        
    }

    public GameObject GetStart()
    {
        //求Start
        GameObject[] Systems;
        Systems = GameObject.FindGameObjectsWithTag("systems");
        List<GameObject> systemTemp = new List<GameObject>();
        foreach (GameObject sys in Systems)
        {
            if (sys.GetComponent<StarSystem>().Owner == PlayerID)
            {
                systemTemp.Add(sys);
            }
        }
        if (systemTemp.Count == 0)
            return null;
        _Start= systemTemp[Random.Range(0, systemTemp.Count)];
        GameManager.Instance._Start = _Start;
       // GameManager.Instance.StartPoint = _Start.transform.position;
        return _Start;
       
    }
    public GameObject GetEnd()
    {
        if (Input.GetMouseButtonDown(0)&&EventSystem.current.IsPointerOverGameObject()==false)
        {
            IsMouseDown =!IsMouseDown;
            RaycastHit2D hit;
            hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector3.forward, 1000f, LayerMask.GetMask("Sys"));
            if (hit.collider != null)
            {
                GameObject target = hit.collider.transform.gameObject;
                StarWindow.SetActive(true);
                if (target.GetComponent<StarSystem>().Owner != 2)
                {
                    End = target;
                    GameManager.Instance.End = End;
                  //  GameManager.Instance.EndPoint = End.transform.position;
                    
                    CanvasPosChange.Instance.ChangePos(target, StarWindow);

                }
            }
            if(!IsMouseDown)
            {
                StarWindow.SetActive(false);

            }

        }
        if (End != null)
            return End;
        else
            return null;
    }

   

   
}



	
          